package com.ruoyi.listener.classification;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ruoyi.common.excel.ExcelListener;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.ValidatorUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.quality.domain.bo.QualityClassificationDataBo;
import com.ruoyi.quality.domain.vo.QualityClassificationDataImportVo;
import com.ruoyi.quality.domain.vo.QualityClassificationDataVo;
import com.ruoyi.quality.domain.vo.QualityClassificationItemsVo;
import com.ruoyi.quality.service.IQualityClassificationDataService;
import com.ruoyi.quality.service.IQualityClassificationItemsService;
import com.ruoyi.quality.service.IQualityUserClassificationService;

import java.math.BigDecimal;
import java.util.List;

import static com.ruoyi.common.core.mapper.BaseMapperPlus.log;

public class ClassificationDataImportListener extends AnalysisEventListener<QualityClassificationDataImportVo> implements ExcelListener<QualityClassificationDataImportVo> {
    private final IQualityClassificationDataService classificationDataService;
    private final IQualityClassificationItemsService classificationItemsService;
    private final IQualityUserClassificationService iQualityUserClassificationService;

    private final Boolean isUpdateSupport;
    private final String operName;
    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public ClassificationDataImportListener(Boolean isUpdateSupport) {
        this.classificationDataService = SpringUtils.getBean(IQualityClassificationDataService.class);
        this.classificationItemsService = SpringUtils.getBean(IQualityClassificationItemsService.class);
        this.iQualityUserClassificationService = SpringUtils.getBean(IQualityUserClassificationService.class);
        this.isUpdateSupport = isUpdateSupport;
        this.operName = LoginHelper.getUsername();
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public ExcelResult<QualityClassificationDataImportVo> getExcelResult() {
        return new ExcelResult<QualityClassificationDataImportVo>() {

            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<QualityClassificationDataImportVo> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }

        };
    }

    @Override
    public void invoke(QualityClassificationDataImportVo classificationDataImportVo, AnalysisContext analysisContext) {
        QualityClassificationDataBo bo = BeanUtil.toBean(classificationDataImportVo,QualityClassificationDataBo.class);
        QualityClassificationDataVo classificationDataVo = this.classificationDataService.validByBo(bo);
        QualityClassificationDataBo classificationDataBo = new QualityClassificationDataBo();
        Long itemsId = classificationDataImportVo.getItemsId();
        QualityClassificationItemsVo classificationItemsVo = this.classificationItemsService.queryById(itemsId);
        try {
            // 验证是否存在这个信息单号
            if (ObjectUtil.isNull(classificationDataVo)) {
                classificationDataBo = BeanUtil.toBean(classificationDataImportVo, QualityClassificationDataBo.class);
                ValidatorUtils.validate(classificationDataBo);
                classificationDataBo.setCreateBy(operName);
                extracted(classificationDataBo, classificationItemsVo);
                classificationDataService.insertByBo(classificationDataBo);
                iQualityUserClassificationService.updatePracticeByDataBo(classificationDataBo);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、得分项目 ").append(classificationDataBo.getItemsId()).append(" 导入成功");
            } else if (isUpdateSupport) {
                Long id = classificationDataVo.getId();
                classificationDataBo = BeanUtil.toBean(classificationDataVo, QualityClassificationDataBo.class);
                classificationDataBo.setId(id);
                ValidatorUtils.validate(classificationDataBo);
                classificationDataBo.setUpdateBy(operName);
                extracted(classificationDataBo, classificationItemsVo);
                classificationDataService.updateByBo(classificationDataBo);
                iQualityUserClassificationService.updatePracticeByDataBo(classificationDataBo);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、项目 ").append(classificationDataBo.getId()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、项目 ").append(classificationDataImportVo.getId()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、得分项目 " + classificationDataImportVo.getUserId() + classificationDataImportVo.getItemsId() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }
    }

    private static void extracted(QualityClassificationDataBo classificationDataBo, QualityClassificationItemsVo classificationItemsVo) {
        Long parentId = classificationItemsVo.getParentId();
        classificationDataBo.setParentId(parentId);
        BigDecimal score = classificationItemsVo.getScore();
        BigDecimal grade = classificationDataBo.getGrade();
        if (grade.compareTo(score) > 0){
            classificationDataBo.setGrade(score);
        }
    }
}
